package com.wisdom.view;

import org.json.JSONException;
import org.json.JSONObject;

import com.hisun.phone.core.voice.Log4Util;
import com.wisdom.MainActivity;
import com.bluecall.sipua.R;
import org.sipdroid.sipua.ui.Settings;

import com.wisdom.VoiceApplication;
import com.wisdom.tools.CCPConfig;
import com.wisdom.tools.HttpUtil;
import com.wisdom.voip.VoiceHelper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {
	public static final int WHAT_INIT_ERROR = 0x201C;
	EditText editPhone;
	EditText editPwd;
	private ProgressDialog mDialog;
	public static final String LOGON_URL = CCPConfig.Mobile_BasicUrl + "/api/mobile/logon";

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		initResourceRefs();
	}

	public void goBack(View view) {
		startActivity(new Intent(LoginActivity.this, WelcomeActivity.class));
		LoginActivity.this.finish();
	}

	public void resetPws(View view) {
		startActivity(new Intent(LoginActivity.this, layout_resetpwd.class));
	}

	void showInitErrDialog() {
		new AlertDialog.Builder(this)
				.setTitle(R.string.str_dialog_init_error_title)
				.setMessage(R.string.str_dialog_init_error_message)
				.setPositiveButton(R.string.dialog_btn, null).create().show();
	}

	public void logon(View view) throws JSONException {

		new LoginTask(editPhone.getText().toString(), editPwd.getText().toString()).execute();
		// mDialog = new ProgressDialog(LoginActivity.this);
		// mDialog.setMessage(getString(R.string.dialoglogon_message_text));
		// mDialog.setCanceledOnTouchOutside(false);
		// mDialog.show();
		// String phone=editPhone.getText().toString();
		// String pwd=editPwd.getText().toString();
		// JSONObject object=new
		// JSONObject("{Phone:\""+phone+"\",Password=\""+pwd+"\"}");
		// JSONObject data= HttpUtil.post(logonUrl, object);
		// mDialog.cancel();
		// if(data==null){
		// Toast.makeText(getApplicationContext(),
		// "未知错误！",Toast.LENGTH_SHORT).show();
		// return;
		// }a
		// if(data.getBoolean("success")){
		// String accessToken=data.getString("AccessToken");
		// String subAccount=data.getString("subAccount");
		// String subToken=data.getString("subToken");
		// String voipAccount=data.getString("voipAccount");
		// String voipPwd=data.getString("voipPwd");
		// String userId=data.getString("userId");
		// String srcPhone=data.getString("srcPhone");
		// String Balance=data.getString("balance");
		//
		// CCPConfig.setConfigProperties("accesstoken", accessToken);
		// CCPConfig.setConfigProperties("sub_account",subAccount);
		// CCPConfig.setConfigProperties("sub_token", subToken);
		// CCPConfig.setConfigProperties("voip_account", voipAccount);
		// CCPConfig.setConfigProperties("voip_password", voipPwd);
		// CCPConfig.setConfigProperties("user_id", userId);
		// CCPConfig.setConfigProperties("src_phone", srcPhone);
		// CCPConfig.setConfigProperties("balance", Balance);
		// CCPConfig.setConfigProperties("password", pwd);
		// CCPConfig.initProperties(getApplicationContext());
		//
		// Editor edit =
		// PreferenceManager.getDefaultSharedPreferences(this).edit();
		// edit.putString(Settings.PREF_USERNAME,CCPConfig.Src_phone);
		// edit.putString(Settings.PREF_PASSWORD,pwd);
		// edit.putString(Settings.PREF_PASSWORD,pwd);
		// edit.putString(Settings.PREF_SERVER,CCPConfig.Sip_Server);
		// edit.putString(Settings.PREF_DOMAIN,CCPConfig.Sip_Server);
		// edit.putString(Settings.PREF_PORT,"5060");
		// edit.commit();
		// startAction();
		// }else{
		// Toast.makeText(getApplicationContext(),
		// "登陆失败："+data.getString("message"),Toast.LENGTH_SHORT).show();
		// }
	}

	void initResourceRefs() {
		editPhone = (EditText) findViewById(R.id.editText_phone);
		editPwd = (EditText) findViewById(R.id.editText_pwd);
		editPhone.setText(CCPConfig.Src_phone);
		editPwd.setText(CCPConfig.Password);
	}

	class SDKInitAsyncTask extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... params) {

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			startAction();
		}
	}

	private void startAction() {

		Intent intent = new Intent();
		intent.setClass(LoginActivity.this, HomeTabHostActivity.class);
		startActivity(intent);
		LoginActivity.this.finish();
	}

	public class LoginTask extends AsyncTask<String, Void, JSONObject> {
		String phone;
		String pwd;
		
		public LoginTask(String telNum, String pwd){
			this.phone = telNum;
			this.pwd = pwd;
		}

		@Override
		protected void onPreExecute() {

			mDialog = new ProgressDialog(LoginActivity.this);
			mDialog.setMessage(getString(R.string.dialoglogon_message_text));
			mDialog.setCanceledOnTouchOutside(false);
			mDialog.show();
			super.onPreExecute();
		}

		@Override
		protected JSONObject doInBackground(String... params) {

			JSONObject object;
			JSONObject data = null;
			try {
				object = new JSONObject("{Phone:\"" + phone + "\",Password=\""
						+ pwd + "\"}");
				data = HttpUtil.post(LOGON_URL, object);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return data;

		}

		@Override
		protected void onPostExecute(JSONObject data) {
			mDialog.cancel();
			if (data == null) {
				Toast.makeText(getApplicationContext(), "未知错误！",
						Toast.LENGTH_SHORT).show();
				return;
			}
			try {
				if (data.getBoolean("success")) {
					String accessToken = data.getString("AccessToken");
					String subAccount = data.getString("subAccount");
					String subToken = data.getString("subToken");
					String voipAccount = data.getString("voipAccount");
					String voipPwd = data.getString("voipPwd");
					String userId = data.getString("userId");
					String srcPhone = data.getString("srcPhone");
					String Balance = data.getString("balance");

					CCPConfig.setConfigProperties("accesstoken", accessToken);
					CCPConfig.setConfigProperties("sub_account", subAccount);
					CCPConfig.setConfigProperties("sub_token", subToken);
					CCPConfig.setConfigProperties("voip_account", voipAccount);
					CCPConfig.setConfigProperties("voip_password", voipPwd);
					CCPConfig.setConfigProperties("user_id", userId);
					CCPConfig.setConfigProperties("src_phone", srcPhone);
					CCPConfig.setConfigProperties("balance", Balance);
					CCPConfig.setConfigProperties("password", pwd);
					CCPConfig.initProperties(getApplicationContext());

					Editor edit = PreferenceManager
							.getDefaultSharedPreferences(LoginActivity.this)
							.edit();
					edit.putString(Settings.PREF_USERNAME, CCPConfig.Src_phone);
					edit.putString(Settings.PREF_PASSWORD, pwd);
					edit.putString(Settings.PREF_SERVER, CCPConfig.Sip_Server);
					edit.putString(Settings.PREF_DOMAIN,
							CCPConfig.Domain_Server);
					edit.putString(Settings.PREF_PORT, "5060");
					edit.commit();
					startAction();
				} else {
					Toast.makeText(getApplicationContext(),
							"登陆失败：" + data.getString("message"),
							Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}
